/**
 * Created by tanbingqin on 2020/9/3.
 */
import { messages } from "share/common";
import React from 'react';
import { connect } from 'react-redux';
import {
  Input, Menu, Spin
} from 'antd';
const { SubMenu } = Menu;
const Search = Input.Search;
import formService from 'containers/setting/form/form.service';
import errorMessage from 'share/errorMessage';
import debounce from 'lodash.debounce'

class MetadataList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      menuList: [],
      selectedItem: {},
      defaultOpenKeys: [],
    };
    this.handleSearch = debounce(this.handleSearch, 500);
  }

  componentDidMount() {
    this.setState({loading: true});
    formService.getMetadata().then(res => {
      this.setState({loading: false});
      this.setDefault(res.data || []);
    }).catch(err => {
      errorMessage(err.response);
      this.setState({loading: false});
    });
  }

  //设置默认选中
  setDefault = (menuList) => {
    const { onSelect } = this.props;
    let selectedItem = {};
    let defaultOpenKeys = [];
    if (menuList && menuList.length) {
      selectedItem = this.getFirstOne(menuList[0], defaultOpenKeys);
    }
    this.setState({menuList, selectedItem, defaultOpenKeys});
    if (onSelect) {
      onSelect(selectedItem);
    }
  };

  //获取metadata下第一个叶子节点
  getFirstOne = (metadata, defaultOpenKeys) => {
    let selectedItem = {};
    if (metadata.standardObjTemplateDTOList && metadata.standardObjTemplateDTOList.length) {
      defaultOpenKeys.push(metadata.id);
      selectedItem = this.getFirstOne(metadata.standardObjTemplateDTOList[0], defaultOpenKeys);
    } else {
      selectedItem = {
        key: `${metadata.id}-${metadata.categoryType}-${metadata.type}`,
        id: metadata.id,
        categoryType: metadata.categoryType,
        type: metadata.type
      };
    }
    return selectedItem;
  };

  handleClick = (obj) => {
    const { onSelect } = this.props;
    let keyList = obj.key.split('-');
    let selectedItem = {
      key: obj.key,
      id: keyList[0],
      categoryType: keyList[1],
      type: keyList[2]
    };
    this.setState({selectedItem});
    //要把selectedItem抛出给父组件
    if (onSelect) {
      onSelect(selectedItem);
    }
  };

  renderMenu = (metadata) => {
    if (metadata.standardObjTemplateDTOList && metadata.standardObjTemplateDTOList.length) {
      return <SubMenu key={metadata.id} title={metadata.name}>
        {metadata.standardObjTemplateDTOList.map(subMetadata => {
          return this.renderMenu(subMetadata);
        })}
      </SubMenu>
    } else {
      return <Menu.Item key={`${metadata.id}-${metadata.categoryType}-${metadata.type}`}>{metadata.name}</Menu.Item>
    }
  };

  handleSearch = (keyword) => {
    this.setState({keyword});
  };

  checkIsHasKeyword = (keyword, metadata) => {
    let arr = [];
    let isHasKeyword = false;
    let tempData = JSON.parse(JSON.stringify(metadata));
    if (metadata.name.indexOf(keyword) > -1) {
      isHasKeyword = true;
      arr.push(tempData);
      return {isHasKeyword, arr}; //无需判断子层直接返回，避免子层被置空
    }
    if (metadata.standardObjTemplateDTOList && metadata.standardObjTemplateDTOList.length) {
      tempData.standardObjTemplateDTOList = [];
      metadata.standardObjTemplateDTOList.forEach(subMetadata => {
        if (this.checkIsHasKeyword(keyword, subMetadata).isHasKeyword) {
          isHasKeyword = true; //不能递归的时候置为false
          tempData.standardObjTemplateDTOList.push(...this.checkIsHasKeyword(keyword, subMetadata).arr);
        }
      });
    }
    isHasKeyword && arr.push(tempData);
    return {isHasKeyword, arr};
  };

  filterMenu = (menuList) => {
    const { keyword } = this.state;
    let arr = [];
    menuList.forEach(metadata => {
      let isHasKeyword = this.checkIsHasKeyword(keyword, metadata).isHasKeyword;
      isHasKeyword && arr.push(...this.checkIsHasKeyword(keyword, metadata).arr);
    });
    return keyword ? arr : menuList;
  };

  render() {
    const { loading, menuList, selectedItem, defaultOpenKeys } = this.state;
    return (
      <div className="metadata">
        <Spin spinning={loading}>
          <div style={{paddingRight: 16}}>
            <Search
              placeholder={messages('request-4.key128')}
              onChange={e => this.handleSearch(e.target.value)}
            />
          </div>
          {!!this.filterMenu(menuList).length && (
            <Menu
              onClick={this.handleClick}
              defaultOpenKeys={defaultOpenKeys}
              selectedKeys={[selectedItem.key]}
              mode="inline"
            >
              {this.filterMenu(menuList).map(metadata => {
                return this.renderMenu(metadata);
              })}
            </Menu>
          )}
          {!this.filterMenu(menuList).length && (
            <div className="no-data">
              {messages('common.empty.text')/*暂无数据*/}
            </div>
          )}
        </Spin>
      </div>
    )
  }
}

MetadataList.PropTypes = {
  onSelect: React.PropTypes.func,
};

MetadataList.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    company: state.login.company
  }
}

export default connect(mapStateToProps)(MetadataList);